import { useFetch } from '#app';
import config from "@/app/config";

const fetchConfig = {
  baseURL: config.apiBase,
  headers: {

  }
}
// 请求体封装
function useGetFetchOptions(options = {}) {
  Object.assign(options, fetchConfig)

  return options
}

function dataFactory(response, resolve, reject) {
  const responseData = response.data._rawValue
  if (responseData.code === 1) {
  } else {
    process.client && ElMessage.error(responseData.msg);
    return reject(responseData);
  }
  resolve(responseData.data)

}
// http请求封装
function useHttp(url, options) {
  options = useGetFetchOptions(options)
  return new Promise((resolve, reject) => {
    useFetch(url, options)  
      .then((response) => {
        dataFactory(response, resolve, reject)
      })
      .catch((err) => {
        const msg = err ? err.data : ''
        process.client && ElMessage.error(msg);

      })
  })

}

const serverRequest = {
  // GET请求
  get: (url, params = {}) => {
    const options = {
      method: 'GET',
      query: params
    }
    return useHttp(url, options)
  },
}

export default serverRequest